/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thoughtworks.go.apiv1.i18n;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 从文件加载翻译数据
 */
public class TranslationLoader {
    private static final Logger LOGGER = LoggerFactory.getLogger(TranslationLoader.class);
    private static final Gson GSON = new Gson();

    /**
     * 从文件加载翻译数据
     * Epic-10: 根据 locale 参数只返回对应语言的翻译
     */
    public static I18nData loadFromFile(String pageName, String locale) {
        try {
            String resourcePath = String.format("/i18n-%s.json", pageName);
            InputStream inputStream = TranslationLoader.class.getResourceAsStream(resourcePath);

            if (inputStream == null) {
                LOGGER.warn("Translation file not found: {}", resourcePath);
                return new I18nData();
            }

            try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
                JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject();

                Map<String, String> zhCN = new HashMap<>();
                Map<String, String> en = new HashMap<>();

                // Epic-10: 根据 locale 参数只加载对应语言的翻译
                if ("all".equals(locale)) {
                    // 加载所有语言的翻译
                    if (jsonObject.has("zh-CN")) {
                        JsonObject zhCNObj = jsonObject.getAsJsonObject("zh-CN");
                        for (String key : zhCNObj.keySet()) {
                            zhCN.put(key, zhCNObj.get(key).getAsString());
                        }
                    }
                    if (jsonObject.has("en")) {
                        JsonObject enObj = jsonObject.getAsJsonObject("en");
                        for (String key : enObj.keySet()) {
                            en.put(key, enObj.get(key).getAsString());
                        }
                    }
                    LOGGER.debug("Loaded all translations for page {}: zh-CN={}, en={}", pageName, zhCN.size(), en.size());
                    return new I18nData(zhCN, en);
                } else if ("zh".equals(locale) && jsonObject.has("zh-CN")) {
                    // 只加载中文翻译
                    JsonObject zhCNObj = jsonObject.getAsJsonObject("zh-CN");
                    for (String key : zhCNObj.keySet()) {
                        zhCN.put(key, zhCNObj.get(key).getAsString());
                    }
                    LOGGER.debug("Loaded translations for page {} and locale {}: zh-CN={}", pageName, locale, zhCN.size());
                    return new I18nData(zhCN, new HashMap<>()); // 只返回中文，英文为空
                } else if ("en".equals(locale) && jsonObject.has("en")) {
                    // 只加载英文翻译
                    JsonObject enObj = jsonObject.getAsJsonObject("en");
                    for (String key : enObj.keySet()) {
                        en.put(key, enObj.get(key).getAsString());
                    }
                    LOGGER.debug("Loaded translations for page {} and locale {}: en={}", pageName, locale, en.size());
                    return new I18nData(new HashMap<>(), en); // 只返回英文，中文为空
                } else {
                    // 如果 locale 不匹配或文件格式不正确，返回空数据
                    LOGGER.warn("Invalid locale '{}' or missing language data for page {}", locale, pageName);
                    return new I18nData();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Failed to load translations for page {} and locale {}: {}", pageName, locale, e.getMessage(), e);
            return new I18nData();
        }
    }
}
